<?php

namespace App\Http\Controllers\Admin;

use App\Common\ApiErrorCode;
use App\Http\Controllers\Controller;
use App\Models\Admin;
use App\Models\Rbac\Menu;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    /**
     * 登录
     */
    public function login(Request $request)
    {
        $validated = $request->validate([
            'username' => 'bail|required|string|max:255',
            'password' => 'bail|required|string|min:6|max:255',
        ]);
        $admin = Admin::query()->where('username', $validated['username'])->first();
        if (! $admin) {
            return apiResponseError([4010, '账号不存在']);
        }

        // 检查账号是否处于锁定状态
        if ($admin->lockout_until && now()->lt($admin->lockout_until)) {
            $remaining = now()->diffForHumans($admin->lockout_until, true);

            return apiResponseError([4230, "账号已锁定，请稍后再试（剩余锁定时间：{$remaining}）", ['remaining' => $remaining]]);
        }

        // 验证密码是否正确
        if (! Hash::check($validated['password'], $admin->password)) {
            // 累加失败次数
            $admin->failed_attempts++;
            // 当失败次数正好达到 5 的倍数时，触发锁定
            if ($admin->failed_attempts % 5 === 0) {
                // 计算当前失败组，组号 = 失败次数/5
                $group = $admin->failed_attempts / 5;
                // 锁定时间：以 5 分钟为基数，按指数增长，但最大不超过 1440 分钟（24小时）
                $lockoutMinutes = min(5 * pow(2, $group - 1), 1440);
                $admin->lockout_until = now()->addMinutes($lockoutMinutes);
            }
            $admin->save();

            return apiResponseError([4010, '密码错误']);
        }

        if ($admin->status != 1) {
            return apiResponseError([4230, '账号状态异常，请联系管理员']);
        }

        // 登录成功后，重置失败次数和锁定状态，并更新上次登录时间和IP地址
        $admin->failed_attempts = 0;
        $admin->lockout_until = null;
        $admin->login_time = now();
        $admin->login_ip = $request->ip();
        $admin->save();

        $token = $admin->createToken($admin->username)->plainTextToken;

        return apiResponse(0, '登录成功', [
            'token' => $token,
//            'userInfo' => $admin,
        ]);
    }

    /**
     * 退出登录
    */
    public function logout(Request $request)
    {
        $request->user()->currentAccessToken()->delete();
        return apiResponse(msg:'退出成功');
    }

    /**
     * 获取当前用户信息
     */
    public function me(Request $request){
        $admin = $request->user();
        if($admin->username === 'admin'){
            $menus = Menu::query()->get();
        }else{
            $permissionNames = $admin->getAllPermissions()->pluck('name')->toArray();
            $menus = Menu::query()->whereIn('name',$permissionNames)->orderBy('sort')->get();
            unset($admin['roles']);
//            $menus = $admin->roles()->with('menus')->get()->pluck('menus')->flatten()->unique('id');
        }
        $admin->menus = $this->buildMenuTree($menus);
        return apiResponse(data: $admin);
    }

    public function updatePassword(Request $request)
    {
        $request->validate([
            'password' => 'required',
            'newPassword' => 'required|min:6',
        ]);

        $admin = auth('admin')->user();

        // 检查当前密码是否正确
        if (!Hash::check($request->password, $admin->password)) {
            return apiResponseError([4010,'原密码不正确']);
        }
        $admin->update(['password' => $request->newPassword]);
        return apiResponse();
    }

    /**
     * 构建菜单树
     * @param $menus
     * @param null $parentId
     * @return array
     */
    private function buildMenuTree($menus, $parentId = null): array
    {
        $menus = $menus->sortBy('sort');
        $tree = [];
        foreach ($menus as $menu) {
            if ($menu->parent_id == $parentId) {
                // 递归查找子菜单
                $children = $this->buildMenuTree($menus, $menu->id);
                // 如果没有子菜单，添加默认的子菜单
                if (empty($children)) {
                    $children = [
                        [
                            'path' => 'index',
                            'component' => $menu->component,
                            'name' => "{$menu->name}Index",
                        ]
                    ];
                }
                // 如果有子菜单，添加到父菜单中
                $menu->children = $children;
                // 将菜单添加到树形结构中
                $tree[] = $menu;
            }
        }
        return $tree;
    }

}
